
using System.Linq;
using AllAgreed.DataLayer.Models;
using AllAgreed.Helpers;

namespace AllAgreed.Models.Users
{
    public class UserRepository : IUserRepository
    {
        public User Save(UserDto user)
        {
            var usr = new User
                {
                    Email = user.Email,
                    Login = user.Login,
                    Ip = user.UserIp,
                    Password = AppHelper.HashAndSolt(user.Password),
                    RoleId = user.RoleId
                };
            using (var db = new AllAgreedEntities())
            {
                db.Users.Add(usr);
                db.SaveChanges();
            }
            return usr;
        }

        public User GetUserByLogin(string login)
        {
            using (var db = new AllAgreedEntities())
            {
                return db.Users.FirstOrDefault(user => user.Login.ToLower() == login);
            }
        }

        public bool ExistUserByLogin(string login)
        {
            using (var db = new AllAgreedEntities())
            {
                var usr = db.Users.FirstOrDefault(user => user.Login.ToLower() == login);
                return usr != null;
            }
        }

        public User[] GetAllUsers()
        {
            using (var db = new AllAgreedEntities())
            {
                return db.Users.Where(u => !u.Hide).ToArray();
            }
        }

        public User GetUserById(int id)
        {
            using (var db = new AllAgreedEntities())
            {
                return db.Users.Where(u => !u.Hide).FirstOrDefault(u => u.UserId == id);
            }
        }

        public User[] GetUsersByQuery(string query)
        {
            using (var db = new AllAgreedEntities())
            {
                return db.Users
                    .Where(u => 
                        !u.Hide && (
                        u.Login.Contains(query) || 
                        u.Name.Contains(query) || 
                        u.LastName.Contains(query) || 
                        u.Email.Contains(query)))
                        .ToArray();
            }
        }
    }
}